import asyncio
import aiohttp
from aiolimiter import AsyncLimiter
import pandas as pd
import logging  # 新增导入logging
from datetime import datetime  # 新增导入datetime

# QPS限制器，每秒最多15个请求
limiter = AsyncLimiter(15, 1)

# 配置日志，输出到文件
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[logging.FileHandler("parallel_api.log", encoding="utf-8")],
)


async def fetch(session, url, data, id_):
    async with limiter:
        send_time = datetime.now()  # 记录发送时间
        async with session.post(url, json={"text": data}) as resp:
            result = await resp.json()
            return_time = datetime.now()  # 记录返回时间
            # 日志记录
            log_msg = (
                f"ID:{id_} | 发送时间:{send_time} | 返回时间:{return_time} | "
                f"输入内容:{data} | 返回内容:{result}"
            )
            logging.info(log_msg)
            return id_, data, result, send_time, return_time


async def main(texts, url):
    results = []
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url, text, id_) for id_, text in texts]
        # asyncio.as_completed能及时收集每个完成的结果
        for coro in asyncio.as_completed(tasks):
            id_, text, result, send_time, return_time = await coro
            print(f"ID:{id_} 结果:{result}")
            results.append((id_, text, result, send_time, return_time))
    return results


def save_results_to_excel(results, filename="results.xlsx"):
    """
    保存结果到Excel文件，包含ID、输入内容、返回内容、发送时间、返回时间
    """
    df = pd.DataFrame(
        results, columns=["ID", "输入内容", "返回内容", "发送时间", "返回时间"]
    )
    df.to_excel(filename, index=False)


def read_texts_from_excel(file_path):
    """
    从Excel文件读取ID和内容，假设第一行为表头，第一列为ID，第二列为内容
    返回 [(id, text), ...] 的列表
    """
    df = pd.read_excel(file_path)
    return list(zip(df.iloc[:, 0], df.iloc[:, 1]))


if __name__ == "__main__":
    url = "http://your.api/endpoint"
    input_excel = "input_texts.xlsx"  # 你的输入Excel文件名
    texts = read_texts_from_excel(input_excel)
    results = asyncio.run(main(texts, url))
    save_results_to_excel(results)
